<template>
  <div class="Article">
    <van-pull-refresh v-model="isPullLoading" @refresh="onRefresh" :success-duration='1000' :success-text='successText'>
       <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          :error.sync="error"
          error-text="请求失败，点击重新加载"
          @load="onLoad"
       >
            <articleItem  v-for="item in list" :key="item.art_id+''" :item="item"></articleItem>
        </van-list>
    </van-pull-refresh>

  </div>
</template>

<script>
import { getChannelArticleAPI } from '@/api/article.js'
import articleItem from '@/components/articleItem.vue'
// import { Toast } from 'vant'
export default {
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      pretimestamp: Date.now(),
      error: false, // 控制错误提示
      isPullLoading: false, // 上拉刷新
      successText: ''
    }
  },
  components: {
    articleItem
  },
  props: {
    channelID: {
      type: Number,
      required: true
    }
  },
  methods: {
    // 下拉加载事件
    async onLoad () {
      try {
        // 1. 发起请求获取数据
        const res = await getChannelArticleAPI({ channel_id: this.channelID, timestamp: this.pretimestamp, with_top: 1 })
        // if (Math.random() > 0.3) {
        //   console.lh(13)
        // }
        // 2. 保存数据 铺设到页面上
        this.pretimestamp = res.pre_timestamp
        this.list.push(...res.results)
        // 2. 加载状态设置结束  loading=false 保证下次触底触发事件
        this.loading = false
        // 3. 数据全部加载 finshed = true
        if (!res.pre_timestamp) {
          this.finished = true
        }
      } catch (error) {
        // Toast.clear()
        this.loading = false
        this.error = true
      }
    },
    // 上拉刷新事件
    async onRefresh () {
      try {
        // 1. 发起请求获取数据
        const res = await getChannelArticleAPI({ channel_id: this.channelID, timestamp: Date.now(), with_top: 1 })
        // 2. 保存数据 铺设到页面上
        this.list.unshift(...res.results)
        // 2. 加载状态设置结束  loading=false 保证下次触底触发事件
        this.isPullLoading = false
        // 3. 数据全部加载 finshed = true
        this.successText = '刷新成功'
      } catch (error) {
        // Toast.clear()
        this.loading = false
        this.error = true
        this.successText = '刷新失败'
      }
    }
  }
}
</script>

<style scoped lang='less'>
.Article {
  // padding-bottom: 100px;
  // vh视口高度 100vh
  height: 80vh;
  overflow: scroll;
}

</style>
